package com.codefish.codefishseckill.security;

import com.codefish.codefishseckill.service.UserService;
import com.codefish.codefishseckill.utils.CookieUtil;
import com.codefish.codefishseckill.utils.ResponseUtil;
import com.codefish.codefishseckill.vo.RespBeanFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/30 下午 05:33
 */
@Component
@Slf4j
public class MyLogOutHandler implements LogoutHandler {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        redisTemplate.delete(UserService.USER_INFO_TOKEN_PREFIX + CookieUtil.getValueByKey(request, CookieUtil.USER_INFO_KEY));
        CookieUtil.setCookie(response, CookieUtil.USER_INFO_KEY, "", 0, "/");
        //ResponseUtil.out(response, RespBeanFactory.success("注销成功"));
        // 重定向到登录页
        try {
            response.sendRedirect("/login");
        } catch (Exception e) {
            log.error("重定向到登录页失败", e);
        }
    }
}
